<template>
  <view class="employee-edit-container">
    <!-- 顶部导航栏 -->
    <!-- <view class="top-bar">
      <text class="title">{{ isEditing ? '编辑员工' : '添加员工' }}</text>
      <view class="right-icon" @click="handleBack">
        <image src="/static/xiugai07_1.png" mode="aspectFit" class="back-icon"></image>
      </view>
    </view> -->
    
    <!-- 表单内容 -->
    <view class="form-container">
      <view class="form-group">
        <text class="label">员工姓名 <text class="required">*</text></text>
        <input type="text" v-model="formData.name" placeholder="请输入员工姓名" class="input-field">
      </view>
      
      <view class="form-group">
        <text class="label">昵称</text>
        <input type="text" v-model="formData.nickname" placeholder="请输入昵称" class="input-field">
      </view>
      
      <view class="form-group">
        <text class="label">编号</text>
        <input type="text" v-model="formData.serial_no" placeholder="请输入编号" class="input-field">
      </view>
      
      <view class="form-group">
        <text class="label">职位 <text class="required">*</text></text>
        <picker @change="bindJobChange" :value="jobIndex" :range="jobs" range-key="name" class="picker-field">
          <view class="picker-display">{{ jobs[jobIndex]?.name || '请选择职位' }}</view>
        </picker>
      </view>
      
      <view class="form-group">
        <text class="label">状态</text>
        <picker @change="bindStatusChange" :value="statusIndex" :range="statuses" range-key="label" class="picker-field">
          <view class="picker-display">{{ statuses[statusIndex]?.label || '请选择状态' }}</view>
        </picker>
      </view>
    </view>
    
    <!-- 提交按钮 -->
    <view class="submit-button-container">
      <button class="submit-button" @click="submitForm">{{ isEditing ? '保存修改' : '添加员工' }}</button>
    </view>
  </view>
</template>

<script>
import store from '@/store'

export default {
  data() {
    return {
      isEditing: false,
      employeeId: '',
      formData: {
        user_id: '',
        name: '',
        nickname: '',
        serial_no: '',
        job_id: '',
        status: 'normal'
      },
      // 职位列表（实际项目中可能需要从API获取）
      jobs: [
        { id: 1, name: '管理员' },
        { id: 2, name: '店长' },
        { id: 3, name: '副店长' },
        { id: 4, name: '初级助教' },
        { id: 5, name: '中级助教' },
        { id: 6, name: '高级助教' }
      ],
      jobIndex: 0,
      // 状态列表
      statuses: [
        { value: 'normal', label: '正常' },
        { value: 'disabled', label: '禁用' }
      ],
      statusIndex: 0
    };
  },
  onLoad(options) {
    // 默认设置用户ID
    if (store.state.user && store.state.user.userInfo && store.state.user.userInfo.id) {
      this.formData.user_id = store.state.user.userInfo.id;
    }
    
    // 检查是否是编辑模式
    if (options.ids) {
      this.isEditing = true;
      this.employeeId = options.ids;
      this.getEmployeeInfo();
    }
  },
  methods: {
    // 获取员工信息（编辑模式下）
    async getEmployeeInfo() {
      try {
        const res = await this.$request({
          url: '/emp/edit',
          method: 'GET',
          params: {
            ids: this.employeeId
          }
        });
        
        if (res.code === 1) {
          const employeeInfo = res.data;
          this.formData = {
            user_id: employeeInfo.user_id || '',
            name: employeeInfo.name || '',
            nickname: employeeInfo.nickname || '',
            serial_no: employeeInfo.serial_no || '',
            job_id: employeeInfo.job_id || '',
            status: employeeInfo.status || 'normal'
          };
          
          // 设置职位索引
          const jobIndex = this.jobs.findIndex(item => item.id === this.formData.job_id);
          this.jobIndex = jobIndex !== -1 ? jobIndex : 0;
          
          // 设置状态索引
          const statusIndex = this.statuses.findIndex(item => item.value === this.formData.status);
          this.statusIndex = statusIndex !== -1 ? statusIndex : 0;
        } else {
          throw new Error(res.msg || '获取员工信息失败');
        }
      } catch (error) {
        console.error('获取员工信息失败:', error);
        uni.showToast({
          title: '获取员工信息失败',
          icon: 'none'
        });
      }
    },
    
    // 职位选择变化
    bindJobChange(e) {
      this.jobIndex = e.detail.value;
      this.formData.job_id = this.jobs[this.jobIndex].id;
    },
    
    // 状态选择变化
    bindStatusChange(e) {
      this.statusIndex = e.detail.value;
      this.formData.status = this.statuses[this.statusIndex].value;
    },
    
    // 表单验证
    validateForm() {
      if (!this.formData.name) {
        uni.showToast({
          title: '请输入员工姓名',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.formData.job_id) {
        uni.showToast({
          title: '请选择职位',
          icon: 'none'
        });
        return false;
      }
      
      return true;
    },
    
    // 提交表单
    async submitForm() {
      // 表单验证
      if (!this.validateForm()) {
        return;
      }
      
      try {
        let url, params;
        
        if (this.isEditing) {
          // 编辑员工
          url = '/emp/edit';
          params = {
            ...this.formData,
            ids: this.employeeId
          };
        } else {
          // 添加员工
          url = '/emp/add';
          params = this.formData;
        }
        
        const res = await this.$request({
          url: url,
          method: 'POST',
          data: params
        });
        
        if (res.code === 1) {
          uni.showToast({
            title: res.msg || (this.isEditing ? '编辑成功' : '添加成功'),
            icon: 'success'
          });
          
          // 延迟返回上一页，让用户看到成功提示
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          throw new Error(res.msg || (this.isEditing ? '编辑失败' : '添加失败'));
        }
      } catch (error) {
        console.error(this.isEditing ? '编辑员工失败:' : '添加员工失败:', error);
        uni.showToast({
          title: error.message || (this.isEditing ? '编辑失败' : '添加失败'),
          icon: 'none'
        });
      }
    },
    
    // 返回上一页
    handleBack() {
      uni.navigateBack();
    }
  }
};
</script>

<style scoped>
.employee-edit-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 30rpx;
  position: relative;
  z-index: 1;
}

/* 顶部导航栏 */
.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 40rpx 30rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  position: relative;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

/* 表单容器 */
.form-container {
  padding: 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
  position: relative;
  z-index: 10;
}

/* 表单组 */
.form-group {
  margin-bottom: 30rpx;
  position: relative;
  z-index: 20;
}

/* 标签样式 */
.label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
}

.required {
  color: #ff3b30;
}

/* 输入框样式 */
.input-field {
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 10rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  background-color: #fff;
  pointer-events: auto;
  z-index: 1;
  height: 84rpx;
}

/* 选择器样式 */
.picker-field {
  width: 100%;
  pointer-events: auto;
  position: relative;
  z-index: 20;
}

.picker-display {
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 10rpx;
  font-size: 28rpx;
  color: #333;
  box-sizing: border-box;
  background-color: #fff;
}

/* 提交按钮容器 */
.submit-button-container {
  padding: 30rpx;
}

/* 提交按钮样式 */
.submit-button {
  width: 100%;
  background-color: #4cd964;
  color: #fff;
  border: none;
  border-radius: 20rpx;
  padding: 24rpx;
  font-size: 32rpx;
  font-weight: bold;
}
</style>